﻿using System;
using System.Collections.Generic;
using Common.Logging;
using Newtonsoft.Json;

namespace User.Api.Helpers
{
    public static class LocalUserTokenHelper
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(LocalUserTokenHelper));

        private const string TokenSignKey = "zxsidjfaois04r50m5tyuiz";
        private const string TokenEncryptKey = "xthgbinhttmkdiny";

        public static string GenerateLocalToken(long userId, string openId)
        {
            var dicts = new Dictionary<string, string>();
            dicts.Add("Id", userId.ToString());
            dicts.Add("OpenId", openId);

            var token = new TokenBuilder(TokenSignKey).Build(dicts);
            //var encryptToken = AesHelper.Encrypt(token, TokenEncryptKey);

            return token;
        }

        public static bool VerifyLocalToken(string token, out long userId, out string openId)
        {
            userId = 0L;
            openId = "";

            try
            {
                //var tokenBytes = Convert.FromBase64String(token.UrlDecode());

                //var descriptToken = Encoding.UTF8.GetString(AesHelper.Decrypt(tokenBytes, TokenEncryptKey));

                Dictionary<string, string> dicts;

                var isVerified = new TokenBuilder(TokenSignKey).Verify(token.UrlDecode(), out dicts);

                if (isVerified)
                {
                    userId = dicts["Id"].ToInt64();
                    openId = dicts["OpenId"];

                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(JsonConvert.SerializeObject(ex));
                return false;
            }
        }
    }
}